package com.likeyoudo.views.activity;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.viewpager2.widget.ViewPager2;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.CacheMemoryStaticUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.android.material.navigation.NavigationView;
import com.likeyoudo.common.BaseActivity;
import com.likeyoudo.common.BaseFragment;
import com.likeyoudo.common.constant.HttpStatus;
import com.likeyoudo.common.enums.IconEnum;
import com.likeyoudo.common.msg.MsgEvent;
import com.likeyoudo.views.R;
import com.likeyoudo.views.api.LoginApi;
import com.likeyoudo.views.api.MenuApi;
import com.likeyoudo.views.enums.PageEnum;
import com.likeyoudo.views.adapter.FragmentAdapter;
import com.likeyoudo.views.fragment.IndexFragment;
import com.likeyoudo.views.fragment.public_service.ApprovalFragment;
import com.likeyoudo.views.type.entity.router.RouterData;
import com.likeyoudo.views.type.entity.system.User;
import com.likeyoudo.views.type.response.GetInfoResponse;
import com.likeyoudo.common.utils.CommonUtils;
import com.likeyoudo.views.utils.HttpRequest;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import cn.hutool.core.util.StrUtil;


public class IndexActivity extends BaseActivity {

    List<BaseFragment> fragmentList;
    ViewPager2 vp2;
    NavigationView nav_view;
    Menu menu;
    List<RouterData> listData;
    List<RouterData> allData;
    List<RouterData> currentData;
    Stack<List<RouterData>> stack;
    DrawerLayout drawer_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 划掉应用则清空所有缓存数据
        CacheMemoryStaticUtils.clear();
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.mine) {
            // 关闭navigationView
            drawer_layout.closeDrawer(GravityCompat.START);
            // 设置fragment为mine页面
            // vp2.setCurrentItem(CommonUtils.findFragmentIndexByClass(fragmentList, MineFragment.class),false);

            // 切换到我的页面
            ActivityUtils.startActivity(MineActivity.class);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_index;
    }

    private void initView() {
        setImmersiveWindows();
        stack = new Stack<>();
        drawer_layout = findViewById(R.id.drawer_layout);

        navigationShowDrawerLayout(drawer_layout);
        // 获取navigationView
        nav_view = findViewById(R.id.nav_view);
        // 绑定选择事件
        nav_view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                // 查询该项没有子项的话执行
                checkItemNoChild(item);
                return true;
            }
        });
        // 获取menu
        menu = nav_view.getMenu();
        fragmentSetup();

        // 请求接口
        request();

        // 刷新按钮
        // showMenu(R.menu.refresh_menu, new Toolbar.OnMenuItemClickListener() {
        //     @Override
        //     public boolean onMenuItemClick(MenuItem item) {
        //         // 重新请求接口
        //         if (item.getItemId() == R.id.refresh) {
        //             request();
        //             ToastUtils.showShort("正在重新请求");
        //         }
        //         return true;
        //     }
        // });

    }

    private void checkItemNoChild(MenuItem item) {
        String s = item.getTitle().toString();
        if ("返回上一级".equals(s)) {
            currentData = stack.pop();
            setupMenu(currentData);
        } else if ("首页".equals(s)) {
            // 关闭当前的navigation_view
            drawer_layout.closeDrawer(GravityCompat.START);
            setTitle("首页");
            // 设置点击状态
            item.setChecked(true);
            // 跳转到首页
            vp2.setCurrentItem(CommonUtils.findFragmentIndexByClass(fragmentList, IndexFragment.class), false);
        } else {
            for (RouterData allDatum : currentData) {
                if (allDatum.getMeta().getTitle().equals(s)) {
                    if (allDatum.getChildren() == null || allDatum.getChildren().isEmpty()) {
                        // 清除所有选中状态
                        clearMenuChecked(menu);
                        // 跳转页面(关闭平滑滚动的动画)
                        vp2.setCurrentItem(getFragmentIndex(fragmentList, item), false);
                        drawer_layout.closeDrawer(GravityCompat.START);
                    } else {
                        // 保存父节点
                        stack.push(currentData);
                        currentData = allDatum.getChildren();
                        setupMenu(currentData);
                    }
                }
            }
        }
    }

    /**
     * 请求接口
     */
    private void request() {
        MenuApi.getRouter();

        // 获取用户信息
        LoginApi.getInfo();
    }

    /**
     * 初始化所有的Fragment到列表中
     */
    private void fragmentSetup() {
        fragmentList = new ArrayList<>();
        // 扫描com.likeyoudo.views.fragment包下的所有Fragment,并创建对象,添加到数组中

        fragmentList.add(new IndexFragment());
        fragmentList.add(new ApprovalFragment());


        // 设置viewPager2
        vp2 = findViewById(R.id.vp2);
        // 关闭左右滑动
        vp2.setUserInputEnabled(false);
        // 创建PageAdapter
        FragmentAdapter adapter = new FragmentAdapter(getSupportFragmentManager(), getLifecycle(), fragmentList);
        // 设置adapter
        vp2.setAdapter(adapter);


        // 设置默认页,title在选中菜单项之后会自动切换
        setTitle("首页");
        vp2.setCurrentItem(CommonUtils.findFragmentIndexByClass(fragmentList, IndexFragment.class), false);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MsgEvent event) {
        if (MenuApi.ROUTER.equals(event.getType())) {
            listData = event.getListData(RouterData.class);

            // allData = new ArrayList<>();
            // RouterDataUtils.openRouters(listData, allData);
            currentData = listData;

            // 获取菜单项数据后创建菜单项
            setupMenu(listData);
        } else if (LoginApi.GET_INFO.equals(event.getType())) {
            GetInfoResponse response = event.getResponse(GetInfoResponse.class);
            if (response.getCode() == HttpStatus.SUCCESS) {
                User user = response.getUser();
                TextView userName = findViewById(R.id.user_name);
                TextView nickName = findViewById(R.id.nick_name);
                userName.setText(user.getUserName());
                nickName.setText(user.getNickName());
                ImageView profile = findViewById(R.id.profile);
                if (StrUtil.isNotBlank(user.getAvatar())) {
                    Glide.with(this).load(HttpRequest.HOST + user.getAvatar()).centerCrop().into(profile);
                }
            } else {
                ToastUtils.showLong(response.getMsg());
            }
        }
    }

    private void setupMenu(List<RouterData> listData) {
        // 清空原有菜单项
        clearMenu();
        if (listData == this.listData) {
            // 添加首页
            MenuItem index = menu.add(Menu.NONE, R.layout.fragment_index, Menu.NONE, "首页");
            if (!index.isChecked() && "首页".equals(getToolBarTitle())) {
                index.setChecked(true);
            }
            index.setIcon(com.likeyoudo.common.R.drawable.ruoyi_icon_dashboard);
        } else {
            // 添加返回上一级
            MenuItem topLevel = menu.add(Menu.NONE, Menu.NONE, Menu.NONE, "返回上一级");
            topLevel.setIcon(com.likeyoudo.common.R.drawable.ruoyi_icon_back);
        }
        for (RouterData listDatum : listData) {
            // 添加到菜单栏
            MenuItem add = menu.add(Menu.NONE, PageEnum.getResId(listDatum.getPath()), Menu.NONE, listDatum.getMeta().getTitle());
            add.setIcon(IconEnum.getResId(listDatum.getMeta().getIcon()));
            if (!add.isChecked() && getToolBarTitle().equals(listDatum.getMeta().getTitle())) {
                add.setChecked(true);
            }
        }
    }

    private void clearMenu() {
        // 清空原有菜单项
        nav_view.inflateMenu(R.menu.activity_index_menu);
        nav_view.getMenu().clear();
    }


}